package com.hyz.reggie.aop;

import com.google.common.util.concurrent.RateLimiter;
import com.hyz.reggie.pojo.AcquireExecption;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 自定义限流注解
 */
@Component
@Aspect
public class AccessLimitAop {

    @Pointcut("@annotation(com.hyz.reggie.anno.AccessLimit)")
    public void pt1(){
    }
    //20.0 代表每秒生成20个令牌
    private RateLimiter rateLimiter = RateLimiter.create(100.0);

    @Around("pt1()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint){
        Object obj = null;
        //前置通知
        //获得令牌
        boolean flag = rateLimiter.tryAcquire();

        if(!flag){ //如果没有获得到令牌，返回一个服务器繁忙即可
            throw new AcquireExecption("服务器繁忙,请稍后访问...");
    }

        try {
            obj=proceedingJoinPoint.proceed();
            //后置通知
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            //异常通知
        }
        //返回null
        return obj;
    }

}

